﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Security.Cryptography;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.RegularExpressions;
using CoreShop.App;
using CoreShop.Library;
using CoreShop.Services;
using System.Windows.Forms;
using CoreShop.Model;
using CoreShop.PrintService;
using SqlSugar;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using Yitter.IdGenerator;
using SqlSugar.Extensions;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;
using Sunny.UI;
using System.Xml;
using NPOI.SS.Formula.Functions;
using NPOI.Util;
using CoreShop.Model.UI;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using static System.Windows.Forms.AxHost;
using Sunny.UI.Win32;
using IWshRuntimeLibrary;
using FastMember;
using PluSoft.Utils;
using System.Threading.Tasks;
using System.Threading;

namespace CoreShop.App
{
    public class ScreemImgService
    {
        /// <summary>
        /// 获取副屏的图片
        /// </summary>
        public void GetScreemImgList(sysuser sysuser, corecmsstore sysStore, corecmsexchange exchange)
        {
            Thread newThread = new Thread(() => GetScreemImgThread(sysuser, sysStore, exchange));
            newThread.Start();
        }

        /// <summary>
        /// 获取副屏的图片
        /// </summary>
        public void GetScreemImgThread(sysuser sysuser, corecmsstore sysStore, corecmsexchange exchange)
        {
            try
            {
                string msg = "";
                ReturnModel result = new PosRemoteServices(AppConstVars.sUrl).GetScreenImage(sysuser, sysStore);
                if (result.Status != ReturnStatus.Success)
                {
                    msg = "获取副屏广告图错误";
                    return;
                }

                ScreemGetImgModelReturnModel Imginfo = result.MessageOrString.JsonToEntity<ScreemGetImgModelReturnModel>();

                if (Imginfo == null || Imginfo.code != 200)
                {
                    msg = "获取副屏广告图错误";
                    return;
                }
                if (Imginfo.data == null || Imginfo.data.Count <= 0)
                {
                    msg = "获取副屏广告图错误";
                    return;
                }

                new corecmsscreenimgService().DeleteAsync(p => p.tenantScreenImgId > 0);

                DateTime screemImgTime = exchange.screemImgTime;

                foreach (var imginfo in Imginfo.data)
                {
                    if (screemImgTime < CommFunc.ConvertToDateTime(imginfo.createTime))
                        screemImgTime = CommFunc.ConvertToDateTime(imginfo.createTime);
                    if (screemImgTime < CommFunc.ConvertToDateTime(imginfo.updateTime))
                        screemImgTime = CommFunc.ConvertToDateTime(imginfo.updateTime);
                    
                    List<corecmsscreenimg> imgList = imginfo.imgList;
                    new corecmsscreenimgService().InsertOrUpdateAsync(imgList);

                    if ((CommFunc.ConvertToDateTime(imginfo.createTime) > exchange.screemImgTime)
                        || (CommFunc.ConvertToDateTime(imginfo.updateTime) > exchange.screemImgTime))
                    {
                        GetScreemImgDowm(imgList);
                    }
                }

                if (screemImgTime != exchange.screemImgTime)
                {
                    exchange.screemImgId = Imginfo.data.Select(p => p.tenantScreenId).Max();
                    exchange.screemImgTime = screemImgTime;
                    new corecmsexchangeServices().UpdateAsync(new corecmsexchange { storeId = sysStore.id, screemImgTime = screemImgTime, screemImgId = exchange.screemImgId });
                }
            }
            catch (Exception ex)
            {

            }            
        }

        /// <summary>
        /// 将副屏图片下载
        /// </summary>
        /// <param name="img"></param>
        public void GetScreemImgDowm(List<corecmsscreenimg> imgList)
        {
            try
            {
                string path = AppConstVars.SecondScreemImg;

                // 判断文件夹是否存在
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                imgList.ForEach(p =>
                {
                    string FileName = p.tenantScreenImgId.ToString();

                    HttpWebRequest httpWebRequest = null;
                    httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(p.imgUrl);
                    httpWebRequest.Method = "Get";//请求方式
                    httpWebRequest.ContentType = "application/json;charset=UTF-8";
                    HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
                    Stream sr = httpWebResponse.GetResponseStream();
                    Stream sw = new FileStream(path + "\\" + FileName + ".png", FileMode.Create);

                    long totalDownloadedByte = 0;
                    byte[] by = new byte[1024 * 1024 * 20];

                    int osize = sr.Read(by, 0, (int)by.Length);
                    while (osize > 0)
                    {
                        totalDownloadedByte = osize + totalDownloadedByte;
                        sw.Write(by, 0, osize);
                        osize = sr.Read(by, 0, (int)by.Length);
                    }
                    sw.Close();
                    sr.Close();

                    if (Program.frmCustShow != null) 
                        Program.frmCustShow.ListImgsInDirectory();
                });
            }
            catch (Exception ex)
            {
                //LogManage.Error($"下载副品广告图片失败:{ex.Message}");
            }
        }

    }
}
